import React, { useState, useMemo, useEffect } from "react";
import { Form, Input, Radio, TreeSelect } from "antd";
import { IconSelectComponent } from "@/components/custom";
import { ModalComponent, InputNumberComponent, CheckboxComponent } from "@/components/iteration";
import PropTypes from "prop-types";

import rules from "@/config/rules";
import { getTreeMenuList } from "@/api/system/menu";

const CatalogFormItems = () => {
  return (
    <>
      <div className="form-item-layout">
        <Form.Item name="menuPath" label="路由地址">
          <Input placeholder="请输入路由地址" />
        </Form.Item>
        <Form.Item name="redirect" label="重定向地址">
          <Input placeholder="请输入重定向地址" />
        </Form.Item>
      </div>
      <div className="form-item-layout">
        <Form.Item name="visible" label="显示状态">
          <Radio.Group>
            <Radio value={0}>显示</Radio>
            <Radio value={1}>隐藏</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="status" label="菜单状态">
          <Radio.Group>
            <Radio value={0}>正常</Radio>
            <Radio value={1}>停用</Radio>
          </Radio.Group>
        </Form.Item>
      </div>
    </>
  );
};

const MenuFormItems = () => {
  return (
    <>
      <div className="form-item-layout">
        <Form.Item name="menuPath" label="路由地址">
          <Input placeholder="请输入路由地址" />
        </Form.Item>
        <Form.Item name="query" label="路由参数">
          <Input placeholder="请输入路由参数" />
        </Form.Item>
      </div>
      <div className="form-item-layout">
        <Form.Item name="component" label="组件路径">
          <Input placeholder="请输入组件路径" />
        </Form.Item>
        <Form.Item name="menuCode" label="权限标识">
          <Input placeholder="请输入权限标识" />
        </Form.Item>
      </div>
      <div className="form-item-layout">
        <Form.Item name="isFrame" label="是否外链">
          <CheckboxComponent label={["否", "是"]} />
        </Form.Item>

        <Form.Item name="isTabClose" label="标签关闭">
          <CheckboxComponent label={["否", "是"]} />
        </Form.Item>
      </div>
      <div className="form-item-layout">
        <Form.Item name="visible" label="显示状态">
          <Radio.Group>
            <Radio value={0}>显示</Radio>
            <Radio value={1}>隐藏</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="status" label="菜单状态">
          <Radio.Group>
            <Radio value={0}>正常</Radio>
            <Radio value={1}>停用</Radio>
          </Radio.Group>
        </Form.Item>
      </div>
    </>
  );
};

const ButtonFormItems = () => {
  return (
    <>
      <div className="form-item-layout">
        <Form.Item name="menuCode" label="权限标识">
          <Input placeholder="请输入权限标识" />
        </Form.Item>
        <Form.Item name="status" label="菜单状态">
          <Radio.Group>
            <Radio value={0}>正常</Radio>
            <Radio value={1}>停用</Radio>
          </Radio.Group>
        </Form.Item>
      </div>
    </>
  );
};

/**
 * 添加/修改信息对话框
 *
 * @param {Object} initialValues 初始化数据
 * @param {Function} callback 回调函数
 * @returns {React.Component} Component
 */
const EditorModelComponent = ({ open, initialValues, onCallback, onCancel, ...resProps }) => {
  const [form] = Form.useForm();
  const isEditor = useMemo(() => initialValues && initialValues.menuId, [initialValues]);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [menuType, setMenuType] = useState(initialValues?.menuType || "CATALOG");
  const [treeData, setTreeData] = useState([]);
  const formElements = {
    CATALOG: <CatalogFormItems />,
    MENU: <MenuFormItems />,
    BUTTON: <ButtonFormItems />,
  };

  useEffect(() => {
    if (open) {
      getTreeMenuList().then((res) => setTreeData(res));
      form.setFieldsValue(initialValues);
    }
    return () => form.resetFields();
  }, [open, initialValues, form]);

  const onModalOK = () => {
    form.validateFields().then(async (values) => {
      setConfirmLoading(true);
      if (isEditor) {
        values.menuId = initialValues.menuId;
      }
      await onCallback(values).finally(() => setConfirmLoading(false));
      onCancel && onCancel();
    });
  };

  const onTreeSelect = (_, values) => {
    const orderIndex = (values.children && values.children[values.children?.length - 1].orderNum) || 0;
    form.setFieldValue("orderNum", orderIndex + 1);
  };

  const handleValuesChange = (changedValues) => {
    const key = Object.keys(changedValues).pop();
    if (key === "component") {
      const value = changedValues[key].split("/").join(":");
      form.setFieldValue("menuCode", value);
    }
  };

  return (
    <ModalComponent
      title={isEditor ? "修改信息" : "添加信息"}
      {...resProps}
      width="800px"
      open={open}
      onOk={onModalOK}
      onCancel={onCancel}
      confirmLoading={confirmLoading}
      destroyOnClose
    >
      <Form
        initialValues={{ parentId: "0", menuType: "CATALOG", isFrame: 0, visible: 0, status: 0 }}
        autoComplete="off"
        form={form}
        colon={false}
        onValuesChange={handleValuesChange}
      >
        <Form.Item name="parentId" label="父菜单ID">
          <TreeSelect
            treeData={[{ key: "0", menuName: "主目录", menuId: "0", children: treeData }]}
            fieldNames={{ label: "menuName", value: "menuId" }}
            onSelect={onTreeSelect}
          />
        </Form.Item>
        <Form.Item name="menuType" label="菜单类型">
          <Radio.Group onChange={({ target }) => setMenuType(target.value)}>
            <Radio value={"CATALOG"}>目录</Radio>
            <Radio value={"MENU"}>菜单</Radio>
            <Radio value={"BUTTON"}>按钮</Radio>
          </Radio.Group>
        </Form.Item>
        {menuType !== "BUTTON" && (
          <Form.Item name="menuIcon" label="菜单图标">
            <IconSelectComponent placeholder="请输入菜单图标" />
          </Form.Item>
        )}
        <div className="form-item-layout">
          <Form.Item name="menuName" label="菜单名称" rules={rules.required}>
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          <Form.Item name="orderNum" label="显示顺序">
            <InputNumberComponent placeholder="请输入显示顺序" />
          </Form.Item>
        </div>
        {formElements[menuType]}
      </Form>
    </ModalComponent>
  );
};
EditorModelComponent.propTypes = {
  open: PropTypes.bool.isRequired,
  initialValues: PropTypes.shape({
    menuId: PropTypes.string || PropTypes.number,
    menuType: PropTypes.string,
  }),
  onCallback: PropTypes.func.isRequired,
  onCancel: PropTypes.func,
};

export default EditorModelComponent;
